<?php

namespace app\index\controller;

use app\lib\enum\Status;
use think\Db;

class Article extends BaseController
{
    //好课列表
    public function goodClassList()
    {
        $ins_id = input("get.ins_id");
        $ins_id=$ins_id!=""?$ins_id:-1;
        $this->assign("ins_id",$ins_id);
        if (request()->isAjax()) {
            $page = input("post.page");
            $limit = config("setting.goodClassNumPerPage");
            $ins_id = input("post.ins_id");
            $acc_id = input("post.acc_id");
            $latitude = input("post.latitude");
            $longitude = input("post.longitude");
            $orderBy = input("post.orderBy");
            $orderBy = $orderBy == -1 ? "distance" : $orderBy;
            $search=input("post.search");

            $latitude = $latitude == -1 ? "30.2744123119" : $latitude;
            $longitude = $longitude == -1 ? "120.4731988907" : $longitude;

            $condition = [];
            $whereCondition = "";

            if ($ins_id != -1) {
                $condition['art_institution_id'] = ['eq', $ins_id];
                $whereCondition .= " and art_institution_id = $ins_id";
            }

            //文章是否过期
            $condition['art_expire_time'] = ['>', time()];
            $whereCondition .= " and art_expire_time > unix_timestamp()";

            //选择类别为好课分类下的文章
            $condition['art_category_id'] = ['in', getGoodClassSubCategoryIds()];
            $whereCondition .= " and art_category_id in " . getGoodClassSubCategoryIdsStr();


            //如果用户已经选择了指定的类别，就按照该类别显示数据
            if ($acc_id != -1) {
                $condition['art_category_id'] = ['eq', $acc_id];
                $whereCondition .= " and art_category_id = $acc_id";
            }

            //审核通过
            $condition['art_ischeck'] = ['eq', Status::on];
            $whereCondition .= " and art_ischeck = " . Status::on;
            //是否显示
            $condition['art_isshow'] = ['eq', Status::on];
            $whereCondition .= " and art_isshow = " . Status::on;

            //显示指定城市下的好课信息
            $cityId = session("cityId");
            $whereCondition .= " and b.ins_city_id = " . $cityId . " ";

            //只显示未被禁用的机构的课程信息
            $whereCondition.=" and b.ins_status = ".Status::on." ";

            //搜索条件显示
            if($search!=-1){
                $whereCondition.=" and art_title like '%".$search."%' ";
            }

            //如果$orderBy==hot，按照热度排序，按照浏览量降序排序
            $sql = "select *,st_distance_sphere(point(%s,%s),point(b.ins_longitude,b.ins_latitude)) as juli  from cms_article a,py_institution b,cms_article_category c where a.art_institution_id=b.ins_id and a.art_category_id=c.acc_id %s  %s  %s";


            if ($orderBy == "distance") {
                $order = " order by art_istop asc, juli asc ,art_sort asc,art_istop asc,art_ishot asc,art_id desc";
            }
            if ($orderBy == "hot") {
                $order = " order by art_istop asc, art_view_times desc ,art_sort asc,art_istop asc,art_ishot asc,art_id desc";
            }

            $limitStr = "limit " . ($page - 1) * $limit . "," . $limit;
            $sql = sprintf($sql, $longitude, $latitude, $whereCondition, $order, $limitStr);
            $goodClassList = Db::query($sql);


            $hasMore = count($goodClassList) == $limit ? Status::on : Status::off;
            $html = "";
            foreach ($goodClassList as $value) {
                $tempStr = ' <li>
						<div class="img">
							<a href="%s"><img src="%s"/></a>
						</div>
						 <a href="%s">
                            <div class="text">
                                <p style="font-weight: bolder;">课程名称：%s</p>
                                <p>所属机构：%s</p>
                                <p>所属类别：%s %s</p>
                                <p class="ptime">%s   <span>%sKM</span>  <span style="margin-right: 54px">%s次预览</span></p>
                            </div>
						</a>
					</li>';
                $url = "/index/Article/goodClassDetail?art_id=" . $value['art_id'];
                $value['bind_institution']['ins_name'] = $value['ins_name'];
                $value['bind_category']['acc_name'] = $value['acc_name'];
                $value['juli'] = round(($value['juli'] / 1000), 2);
                $value['art_thumb']=$value['art_thumb']?$value['art_thumb']:cache("webInfo")['web_good_class_default_image'];
                $topHtml=$value['art_istop']==Status::on?"<span class=\"topPosition\">置顶</span>":" ";
                $tempHtml = sprintf($tempStr, $url, $value['art_thumb'], $url, $value['art_title'], $value['bind_institution']['ins_name'], $value['bind_category']['acc_name'], $topHtml,date("Y-m-d", $value['art_create_time'])
                    , $value['juli'], $value['art_view_times']);
                $html .= $tempHtml;
            }
            $data = [
                "html" => $html,
                "hasMore" => $hasMore
            ];

            $this->success("", "", $data);
        }

        if (!session("cityId")) {
            //如果没有选择城市，就跳转到首页
            $this->redirect("index/index/index");
        }

        //用户可以在机构页面 查看这个机构所有的好课信息
        $ins_id = $ins_id != "" ? $ins_id : -1;
        $this->assign("ins_id", $ins_id);


        //用户选择不同分类下的好课列表
        $acc_id = input("get.acc_id");
        $acc_id = $acc_id != "" ? $acc_id : -1;
        $this->assign("acc_id", $acc_id);

        $acc_name = "全部分类";
        if ($acc_id != -1) {
            $categoryInfo = model("CmsArticleCategory")->find($acc_id);
            $acc_name = $categoryInfo['acc_name'];
        }
        $this->assign("acc_name", $acc_name);

        //获取orderBy属性
        $orderBy = input("get.orderBy");
        $orderBy = $orderBy != "" ? $orderBy : -1;
        $this->assign("orderBy", $orderBy);

        //获取搜索的标题内容
        $search=input("get.art_title");
        $search==""?"-1":$search;
        $this->assign("search",$search);

        //返回SDK参数
        $this->assign("SDKParams", getSDKParams());
        return view();
    }


    public function goodClassDetail()
    {
        $art_id = input("get.art_id");
        $articleInfo = model("CmsArticle")->with("bindCategory,bindInstitution")->find($art_id);
        //文章浏览量+1
        articleViewTimesAdd($articleInfo, $art_id);


        //判断好课是否存在购买地址，如果存在购买地址，一定显示详情页面
        if($articleInfo['art_url']!=""&&$articleInfo['art_buy_url']==""){
            //跳转
            $this->redirect($articleInfo['art_url']);
            return true;
        }




        //处理用户用户分享的数据
        $articleInfo['desc'] = getStringFromRichText($articleInfo['art_content']);
        $articleInfo['url'] = getUrl();
        $articleInfo['imageUrl'] = "http://" . $_SERVER['SERVER_NAME'] . str_replace("\\","/",$articleInfo['art_thumb']);
        $this->assign("articleInfo", $articleInfo);
        $this->assign("SDKParams", getSDKParams());







        //如果存在，则不展示art_content，显示一个跳转按钮
        //如果不存在，显示art_content
        $hasArtUrl=true;
        $hasBuyUrl=true;
        if($articleInfo['art_url']===""||$articleInfo['art_url']===null){
            $hasArtUrl=false;
        }
        if($articleInfo['art_buy_url']===""){
            $hasBuyUrl=false;
        }

        $this->assign("hasBuyUrl",$hasBuyUrl);
        $this->assign("hasArtUrl",$hasArtUrl);
        return view();
    }

    //好文列表
    public function goodArticleList()
    {
        if (request()->isAjax()) {
            $page = input("post.page");
            $limit = config("setting.goodArticleNumPerPage");
            $ins_id = input("post.ins_id");
            $orderBy = input("post.orderBy");
            $acc_id = input("post.acc_id");
            $art_title=input("post.art_title");


            $condition = [];

            if ($ins_id != -1 && $ins_id != "") {
                $condition['art_institution_id'] = ['eq', $ins_id];
            }


            //文章是否过期
            $condition['art_expire_time'] = ['>', time()];
            //选择类别为好课分类下的文章
            $condition['art_category_id'] = ['in', getGoodArticleSubCategoryIds()];

            //如果限制了文章分类
            if ($acc_id != -1) {
                $condition['art_category_id'] = ['eq', $acc_id];
            }

            //审核通过
            $condition['art_ischeck'] = ['eq', Status::on];
            //是否显示
            $condition['art_isshow'] = ['eq', Status::on];

            $orderBy = $orderBy == -1 ? "hot" : $orderBy;
            if($art_title!=-1&&$art_title!=""){
                $condition['art_title']=['like',"%".$art_title."%"];
            }



            //按照浏览量（热度）降序
            if ($orderBy == "hot") {
                $goodArticleList = model("CmsArticle")->with("bindCategory")->where($condition)
                    ->page($page, $limit)
                    ->order("art_istop", "asc")
                    ->order("art_view_times", "desc")
                    ->order("art_ishot", "asc")
                    ->order("art_id", "desc")
                    ->select();
            } else {
                $goodArticleList = model("CmsArticle")->with("bindCategory")->where($condition)
                    ->page($page, $limit)
                    ->order("art_istop", "asc")
                    ->order("art_id", "desc")
                    ->order("art_ishot", "asc")
                    ->select();
            }


            $hasMore = count($goodArticleList) == $limit ? Status::on : Status::off;
            $html = "";
            foreach ($goodArticleList as $value) {
                $tempStr = '  <li>
                <a href="%s">
                    <div class="card">
                        <p style="color:#000;font-size: 28px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;width: 500px">%s %s</p>
                        <p style="margin-top: 7px">
                            <span>%s</span>
                            <span style="margin-left: 120px">%s</span>
                            <span style="margin-left: 120px">%s次浏览</span>
                        </p>
                    </div>
                </a>
            </li>';

                $url = "/index/Article/goodArticleDetail?art_id=" . $value['art_id'];
                $topHtml=$value['art_istop']==Status::on?"<span class=\"topPosition\">置顶</span>":"";

                $tempHtml = sprintf($tempStr, $url, $value['art_title'], $topHtml,$value['bind_category']['acc_name'],
                    date("Y-m-d", $value['art_create_time']),
                    $value['art_view_times']);
                $html .= $tempHtml;
            }
            $data = [
                "html" => $html,
                "hasMore" => $hasMore
            ];

            $this->success("", "", $data);
        }

        //获取分类条件
        $acc_id = input("get.acc_id");
        $acc_id = $acc_id == "" ? -1 : $acc_id;
        $acc_name = "";
        if ($acc_id != -1) {
            $info = model("CmsArticleCategory")->find($acc_id);
            $acc_name = $info['acc_name'];
        } else {
            $acc_name = "全部分类";
        }
        $this->assign("acc_id", $acc_id);
        $this->assign("acc_name", $acc_name);

        //获取排序条件
        $orderBy = input("get.orderBy");
        $orderBy = $orderBy != "" ? $orderBy : -1;
        $this->assign("orderBy", $orderBy);

        //获取搜索条件
        $art_title=input("get.art_title");
        $art_title=$art_title==""?-1:$art_title;
        $this->assign("art_title",$art_title);

        return view();
    }

    //好文详情
    public function goodArticleDetail()
    {
        $art_id = input("get.art_id");
        $articleInfo = model("CmsArticle")->with("bindCategory,bindInstitution")->find($art_id);
        //文章浏览量+1
        articleViewTimesAdd($articleInfo, $art_id);
        //判断是否需要跳转到其他的页面
        $art_url = $articleInfo['art_url'];
        if ($art_url) {
            $this->redirect($art_url);
        }
        //处理用户用户分享的数据
        $articleInfo['desc'] = getStringFromRichText($articleInfo['art_content']);
        $articleInfo['url'] = getUrl();
        $articleInfo['imageUrl'] = "http://" . $_SERVER['SERVER_NAME'] . str_replace("\\","/",$articleInfo['art_thumb']);
        $this->assign("articleInfo", $articleInfo);
        $this->assign("SDKParams", getSDKParams());
        return view();
    }
}
